package org.example.ch05.service;

import org.apache.ibatis.session.SqlSession;
import org.example.ch05.entity.User;
import org.example.ch05.mapper.UserMapper;
import org.example.ch05.util.MybatisUtils;

import java.util.List;
import java.util.Map;

/**
 * ClassName: UserService
 * Description:
 *
 * @Author zjl
 * @Create 2025/04/23 15:00
 * @Version 1.0
 */
public class UserService {

    public List<User> getUser(Map<String, Object> params) {
        try (SqlSession session = MybatisUtils.getSqlSession()) {
            return session.getMapper(UserMapper.class).getUser(params);
        }
    }

    public List<User> listUserById(List<Integer> ids) {
        try (SqlSession session = MybatisUtils.getSqlSession()) {
            return session.getMapper(UserMapper.class).listUserById(ids);
        }
    }

    public void update(User user) {
        try (SqlSession session = MybatisUtils.getSqlSession()) {
            session.getMapper(UserMapper.class).update(user);
        }
    }

    public void batchInsert(List<User> users) {
        SqlSession session = MybatisUtils.getSqlSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.batchInsert(users);
            session.commit();
        } catch (RuntimeException e) {
            session.rollback();
            throw new RuntimeException();
        } finally {
            session.close();
        }
    }

    public void batchDelete(List<Integer> ids) {
        SqlSession session = MybatisUtils.getSqlSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.batchDelete(ids);
            session.commit();
        } catch (RuntimeException e) {
            session.rollback();
            throw new RuntimeException();
        } finally {
            session.close();
        }
    }
}
